<!-- 新增组别 -->
<template>
  <el-form
    ref="eventGroupsVO"
    :model="eventGroupsVO"
    :rules="eventGroupsVO_Rules"
    label-width="110px"
    size="mini"
    @submit.native.prevent
  >
    <el-row :gutter="15">
      <el-col :span="24" class="form_item">
        <el-form-item label="组别名称" prop="name">
          <el-input
            v-model.trim="eventGroupsVO.name"
            placeholder="请输入组别名称"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="15">
      <el-col :span="13" class="form_item">
        <el-form-item label="年龄区间" prop="startBirthDate">
          <el-date-picker
            v-model="eventGroupsVO.startBirthDate"
            type="date"
            style="width: 100%"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="开始日期"
          />
        </el-form-item>
      </el-col>
      <el-col :span="11" class="form_item">
        <el-form-item label="" label-width="0" prop="endBirthDate">
          <el-date-picker
            v-model="eventGroupsVO.endBirthDate"
            type="date"
            style="width: 100%"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="结束日期"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <template v-if="category.hasGroup">
      <!-- TODO 拆分需求用 -->
      <!-- 团体竞技  和 混合团体竞技-->
      <template v-if="category.preEventTypeCode === 'CompetitiveTeam' || category.preEventTypeCode === 'MixedCompetitiveTeam'">
        <!-- 团体竞技 -->
        <template v-if="!isMixed">
          <el-row :gutter="15">
            <el-col :span="24" class="form_item">
              <el-form-item label="男子分组级别" prop="level_m">
                <el-input

                  v-model.trim="eventGroupsVO.level_m"
                  placeholder="请填写男子分组级别，如：20KG-45KG"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="男子级别拆分" prop="manList">
                <el-row>
                  <el-col v-for="(item, index) in (category.maxTeamMembersCount > 10 ? 10 : category.maxTeamMembersCount)" :key="index" :span="6" class="form_item_Section">
                    <el-input
                      v-model.trim="eventGroupsVO.manList[index]"
                      placeholder="请填写"
                      class="form_item_input"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="form_item">
              <el-form-item label="女子分组级别" prop="level_w">
                <el-input

                  v-model.trim="eventGroupsVO.level_w"
                  placeholder="请填写女子分组级别，如：20KG-45KG"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="女子级别拆分" prop="womenList">
                <el-row>
                  <el-col v-for="(item, index) in (category.maxTeamMembersCount > 10 ? 10 : category.maxTeamMembersCount) " :key="index" :span="6" class="form_item_Section">
                    <el-input
                      v-model.trim="eventGroupsVO.womenList[index]"
                      placeholder="请填写"
                      class="form_item_input"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- 混合团体竞技 -->
        <template v-else>
          <el-row :gutter="15">
            <el-col :span="24" class="form_item">
              <el-form-item label="分组级别" prop="level_n">
                <el-input
                  v-model.trim="eventGroupsVO.level_n"
                  placeholder="请填写分组级别，如：20KG-45KG"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="级别拆分" prop="mixList">
                <el-row>
                  <el-col v-for="(item, index) in (category.maxTeamMembersCount > 10 ? 10 : category.maxTeamMembersCount)" :key="index" :span="6" class="form_item_Section">
                    <el-input
                      v-model.trim="eventGroupsVO.mixList[index]"
                      placeholder="请填写"
                      class="form_item_input"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </template>
      <template v-else>
        <template v-if="!isMixed">
          <el-row :gutter="15">
            <el-col :span="24" class="form_item">
              <el-form-item label="男子级别" prop="level_m">
                <el-input
                  v-model.trim="eventGroupsVO.level_m"
                  placeholder="请填写男子级别，级别间用 ',' 隔开（例如级别一,级别二）"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24" class="form_item">
              <el-form-item label="女子级别" prop="level_w">
                <el-input
                  v-model.trim="eventGroupsVO.level_w"
                  placeholder="请填写女子级别，级别间用 ',' 隔开（例如级别一,级别二）"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-row :gutter="15">
            <el-col :span="24" class="form_item">
              <el-form-item label="具体级别" prop="level_n">
                <el-input
                  v-model.trim="eventGroupsVO.level_n"
                  placeholder="请填写级别，级别间用 ',' 隔开（例如级别一,级别二）"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </template>
      <!-- </template> -->
    </template>
  </el-form>
</template>
<script>
/**
 * 关于显示具体级别、男子级别、女子级别、是否显示级别的说明
 * (1) 不显示级别 hasGroup === false （非重竞技无组）
 *  - 此种情况默认显示一种级别，name取小项name + 组别name
 *  - 性别根据外面情况 (如下)
 * (2) 显示级别 hasGroup === true （重竞技、非重竞技有组）
 *  - 此种情况默认显示一种级别，name取小项name + 组别name
 * (3) 性别设置
 *  - 非混合: 男子级别(M)、女子级别(W)
 *  - 混合  : 具体级别 - categoryVO.genderCode
 **/
import { mapState, mapActions } from 'vuex';
import { SiSTKWEventsManagementEventGroupDTO_Rules } from '@/lib/validate/events';
export default {
  props: {
    category: {
      type: Object,
      required: false,
      default: function() {
        return {};
      }
    },
    eventGroup: {
      type: Object,
      required: false,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      title: '添加组别',
      loading: false,
      dialogVisible: false,
      // 是否显示级别
      showEventLevel: true,
      // 是否是混合
      isMixed: true,
      // 组别
      eventGroupsVO: {
        name: '',
        startBirthDate: '',
        endBirthDate: '',
        level_m: '',
        level_w: '',
        level_n: '',
        manList: [],
        womenList: [],
        mixList: []
      },
      manList: [],
      womenList: [],
      eventGroupsVO_Rules: new SiSTKWEventsManagementEventGroupDTO_Rules()
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  watch: {
    eventGroup() {
      this.init();
    },
    // 根据队伍最大人数处理显示可拆分的数量
    'category.maxTeamMembersCount': {
      handler(val) {
        this.eventGroupsVO.manList = [];
        this.eventGroupsVO.womenList = [];
        this.eventGroupsVO.mixList = [];
        for (let i = 0; i < (val > 10 ? 10 : val); i++) {
          // const obj1 = { value: '' };
          // const obj2 = { value: '' };
          this.eventGroupsVO.manList.push('');
          this.eventGroupsVO.womenList.push('');
          this.eventGroupsVO.mixList.push('');
        }
        console.log(this.eventGroupsVO.manList);
        console.log('eventGroupsVO.mixList', this.eventGroupsVO.mixList);
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getDict();
    this.init();
    this.initRules();
    console.log(this.category);
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    test() {
      console.log('manList', this.manList);
      console.log('womenList', this.womenList);
    },
    init() {
      const level_list = this.handleEchoEventsLevel(this.eventGroup.events || []);
      console.log(this.eventGroup.events);
      console.log(!this.eventGroup.events);
      if (!this.eventGroup.events) {
        this.getMaxTeamMembersCount();
      }
      this.eventGroupsVO = {
        name: this.eventGroup.name || '',
        startBirthDate: this.eventGroup.startBirthDate && this.eventGroup.startBirthDate.substring(0, 10) || '',
        endBirthDate: this.eventGroup.endBirthDate && this.eventGroup.endBirthDate.substring(0, 10) || '',
        level_m: level_list.level_m,
        level_w: level_list.level_w,
        level_n: level_list.level_n,
        manList: this.eventGroupsVO.manList,
        womenList: this.eventGroupsVO.womenList,
        mixList: this.eventGroupsVO.mixList
      };
      // 设置是否显示级别
      this.showEventLevel = this.category.hasGroup;
      // 设置是否为混合
      this.isMixed = this.handleIsMixed();
      this.$nextTick(() => {
        this.$refs.eventGroupsVO && this.$refs.eventGroupsVO.clearValidate();
      });
    },
    getMaxTeamMembersCount () {
      const _this = this;
      this.eventGroupsVO.manList = [];
      this.eventGroupsVO.womenList = [];
      this.eventGroupsVO.mixList = [];
      for (let i = 0; i < (_this.category.maxTeamMembersCount > 10 ? 10 : _this.category.maxTeamMembersCount); i++) {
        // const obj1 = { value: '' };
        // const obj2 = { value: '' };
        _this.eventGroupsVO.manList.push('');
        _this.eventGroupsVO.womenList.push('');
        _this.eventGroupsVO.mixList.push('');
      }
    },
    initRules() {
      const _this = this;
      this.eventGroupsVO_Rules.startBirthDate.push({
        validator(rule, value, callback) {
          const _startBirthDate = value && new Date(value) || '';
          const _endBirthDate = _this.eventGroupsVO.endBirthDate && new Date(_this.eventGroupsVO.endBirthDate.substring(0, 10)) || '';
          if (_startBirthDate && _endBirthDate && _startBirthDate > _endBirthDate) {
            callback(new Error('开始日期不能大于结束日期'));
          }
          callback();
        },
        trigger: 'change'
      });
      this.eventGroupsVO_Rules.endBirthDate.push({
        validator(rule, value, callback) {
          const _startBirthDate = _this.eventGroupsVO.startBirthDate && new Date(_this.eventGroupsVO.startBirthDate.substring(0, 10)) || '';
          const _endBirthDate = value && new Date(value) || '';
          if (_startBirthDate && _endBirthDate && _startBirthDate > _endBirthDate) {
            callback(new Error('结束日期不能小于开始日期'));
          }
          callback();
        },
        trigger: 'change'
      });
    },
    // 处理回显的级别
    handleEchoEventsLevel(events) {
      const _this = this;
      let level_m = '';
      let level_w = '';
      let level_n = '';
      console.log('events', events);
      for (let i = 0; i < events.length; i++) {
        const item = events[i];
        // 排序_sortObj
        // 因为字段不同，需做两套。。。。。
        if (item.weightClassNames && item.weightClassNames.length > 0) {
          item.weightClassNames.sort((a, b) => a.sortOrder - b.sortOrder);
        }
        if (item.weightClasses && item.weightClasses.length > 0) {
          item.weightClasses.sort((a, b) => a.sortOrder - b.sortOrder);
        }
        if (item.genderCode === 'W') {
          level_w += item.name + ',';
          if (item.weightClassNames && item.weightClassNames.length > 0) {
            _this.eventGroupsVO.womenList = item.weightClassNames.map(function(jtem, index) {
              return jtem;
            });
          }
          if (item.weightClasses && item.weightClasses.length > 0) {
            _this.eventGroupsVO.womenList = item.weightClasses.map(function(jtem, index) {
              return jtem.name;
            });
          }
        } else if (item.genderCode === 'M') {
          level_m += item.name + ',';
          if (item.weightClassNames && item.weightClassNames.length > 0) {
            _this.eventGroupsVO.manList = item.weightClassNames.map(function(jtem, index) {
              return jtem;
            });
          }
          if (item.weightClasses && item.weightClasses.length > 0) {
            _this.eventGroupsVO.manList = item.weightClasses.map(function(jtem, index) {
              return jtem.name;
            });
          }
        } else {
          level_n += item.name + ',';
          if (item.weightClassNames && item.weightClassNames.length > 0) {
            _this.eventGroupsVO.mixList = item.weightClassNames.map(function(jtem, index) {
              return jtem;
            });
          }
          if (item.weightClasses && item.weightClasses.length > 0) {
            _this.eventGroupsVO.mixList = item.weightClasses.map(function(jtem, index) {
              return jtem.name;
            });
          }
        }
      }
      level_m = level_m.length > 0 ? level_m.substring(0, level_m.length - 1) : level_m;
      level_w = level_w.length > 0 ? level_w.substring(0, level_w.length - 1) : level_w;
      level_n = level_n.length > 0 ? level_n.substring(0, level_n.length - 1) : level_n;

      return {
        level_m: level_m,
        level_w: level_w,
        level_n: level_n
      };
    },
    // 处理是否为混合
    handleIsMixed() {
      for (let i = 0; i < this.dict.preEventType.length; i++) {
        const item = this.dict.preEventType[i];
        if (item.code === this.category.preEventTypeCode) {
          if ('isMixed' in item.value) {
            return item.value.isMixed;
          } else {
            return item.code.indexOf('Mixed') > -1;
          }
        }
      }
    },
    // 处理级别
    handleEventsLevel(level, genderCode) {
      level = level && level.split(',') || [];
      level = level.filter(item => item);
      return level.map(item => {
        return {
          genderCode: genderCode,
          name: item
        };
      });
    },
    // 提交
    submitGroupInfo() {
      const _this = this;
      return new Promise((resolve, reject) => {
        this.$refs.eventGroupsVO.validate(valid => {
          if (!valid) return;
          let level_m = [];
          let level_w = [];
          let level_n = [];
          // 无组别直接默认一组
          if (this.category.hasGroup) {
            if (this.category.preEventTypeCode === 'CompetitiveTeam' || this.category.preEventTypeCode === 'MixedCompetitiveTeam') {
              if (this.isMixed) {
                level_n = {
                  genderCode: this.category.genderCode,
                  name: this.eventGroupsVO.level_n,
                  weightClassNames: this.eventGroupsVO.mixList.length > _this.category.maxTeamMembersCount ? this.eventGroupsVO.mixList.slice(0, _this.category.maxTeamMembersCount) : this.eventGroupsVO.mixList
                };
              } else {
                level_m = {
                  genderCode: 'M',
                  name: this.eventGroupsVO.level_m,
                  weightClassNames: this.eventGroupsVO.manList.length > _this.category.maxTeamMembersCount ? this.eventGroupsVO.manList.slice(0, _this.category.maxTeamMembersCount) : this.eventGroupsVO.manList
                };
                level_w = {
                  genderCode: 'W',
                  name: this.eventGroupsVO.level_w,
                  weightClassNames: this.eventGroupsVO.womenList.length > _this.category.maxTeamMembersCount ? this.eventGroupsVO.womenList.slice(0, _this.category.maxTeamMembersCount) : this.eventGroupsVO.womenList
                };
              }
            } else {
              level_m = this.handleEventsLevel(this.eventGroupsVO.level_m, 'M');
              level_w = this.handleEventsLevel(this.eventGroupsVO.level_w, 'W');
              level_n = this.handleEventsLevel(this.eventGroupsVO.level_n, this.category.genderCode);
            }
          } else {
            level_m = this.isMixed ? [] : [{ genderCode: 'M', name: '' }]; this.handleEventsLevel('', 'M');
            level_w = this.isMixed ? [] : [{ genderCode: 'W', name: '' }]; this.handleEventsLevel('', 'W');
            level_n = this.isMixed ? [{ genderCode: this.category.genderCode, name: '' }] : [];
          }
          const events = [].concat(level_m, level_w, level_n);
          for (let i = 0; i < events.length; i++) {
            const item = events[i];
            item.sortOrder = i;
          }
          this.eventGroupsVO.events = events;
          resolve(this.eventGroupsVO);
        });
      });
    },
    calcGroupInfo() {
      const _this = this;
      return new Promise((resolve, reject) => {
        let level_m = [];
        let level_w = [];
        let level_n = [];
        // 无组别直接默认一组
        if (_this.category.hasGroup) {
          if (_this.category.preEventTypeCode === 'CompetitiveTeam' || _this.category.preEventTypeCode === 'MixedCompetitiveTeam') {
            if (_this.isMixed) {
              level_n = {
                genderCode: _this.category.genderCode,
                name: _this.eventGroupsVO.level_n,
                weightClassNames: _this.eventGroupsVO.mixList
              };
            } else {
              level_m = {
                genderCode: 'M',
                name: _this.eventGroupsVO.level_m,
                weightClassNames: _this.eventGroupsVO.manList
              };
              level_w = {
                genderCode: 'W',
                name: _this.eventGroupsVO.level_w,
                weightClassNames: _this.eventGroupsVO.womenList
              };
            }
          } else {
            level_m = _this.handleEventsLevel(_this.eventGroupsVO.level_m, 'M');
            level_w = _this.handleEventsLevel(_this.eventGroupsVO.level_w, 'W');
            level_n = _this.handleEventsLevel(_this.eventGroupsVO.level_n, _this.category.genderCode);
          }
        } else {
          level_m = _this.isMixed ? [] : this.handleEventsLevel(`${_this.category.name || ''}${_this.eventGroupsVO.name || ''}`, 'M');
          level_w = _this.isMixed ? [] : this.handleEventsLevel(`${_this.category.name || ''}${_this.eventGroupsVO.name}`, 'W');
          level_n = _this.isMixed ? this.handleEventsLevel(`${_this.category.name || ''}${_this.eventGroupsVO.name}`, _this.category.genderCode) : [];
        }
        const events = [].concat(level_m, level_w, level_n);
        for (let i = 0; i < events.length; i++) {
          const item = events[i];
          item.sortOrder = i;
        }
        _this.eventGroupsVO.events = events;
        // 维护
        if (this.category.id) {
          _this.eventGroupsVO.categoryId = _this.category.id;
        }
        resolve(_this.eventGroupsVO);
      });
    }
  }
};
</script>
<style scoped lang="scss">
  .form_item_Section{
    // display: flex;
    // justify-content: flex-start;
    // flex-wrap: wrap;
    padding-left: 10px;
    margin-bottom: 5px;
  }
</style>
